package com.m3839.sdk.common.widget.richtext;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 适配行间距不一致问题
 *
 * @author 徐智伟
 * @create 2020-03-27
 */
@SuppressLint("AppCompatCustomView")
public class LineSpaceExtraTextView extends TextView {

  public LineSpaceExtraTextView(Context context) {
    super(context);
  }

  public LineSpaceExtraTextView(Context context,
                                AttributeSet attrs) {
    super(context, attrs);
  }

  public LineSpaceExtraTextView(Context context, AttributeSet attrs,
                                int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  /**
   * 排除每行文字间的padding
   *
   * @param text
   */
  public void setCustomText(CharSequence text) {
    if (text == null) {
      return;
    }

    // 获得视觉定义的每行文字的行高
    int lineHeight = (int) getTextSize();

    SpannableStringBuilder ssb ;
    if (text instanceof SpannableStringBuilder) {
      ssb = (SpannableStringBuilder) text;
      // 设置LineHeightSpan
      ssb.setSpan(new ExcludeInnerLineSpaceSpan(lineHeight),
          0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
      ssb = new SpannableStringBuilder(text);
      // 设置LineHeightSpan
      ssb.setSpan(new ExcludeInnerLineSpaceSpan(lineHeight),
          0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    // 调用系统setText()方法
    setText(ssb);
  }
}
